<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="收费站" prop="deptId" v-if="deptId==101">
        <el-tree-select v-model="queryParams.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id"
          class="margin-right" placeholder="请选择部门" check-strictly clearable @change="bindChangeTree($event,'deptId')" />
      </el-form-item>
      <el-form-item label="学习类型" prop="trainTime" v-if="type==2">
        <el-select style="width:100%" v-model="queryParams.studyType" placeholder="请选择学习类型" >
                <el-option v-for="dict in study_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
      </el-form-item>
      <el-form-item label="学习时间" prop="trainTime">
        <el-date-picker clearable v-model="queryParams.trainTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择学习时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['coordination:coo_train:add']">新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['coordination:coo_train:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Menu" @click="handleStatistics">统计</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="coo_trainList" @selection-change="handleSelectionChange" show-overflow-tooltip>
      <el-table-column type="index" width="65" align="center" label="序号" />

      <el-table-column label="收费站" align="center" prop="deptName" v-if="deptId==101" />
      <el-table-column label="学习类型" align="center" prop="studyType"  v-if="type==2">
      <template #default="scope">
              <el-tag :type="getTagStyle(scope.row.studyType)" v-if="scope.row.studyType">
              <dict-tag :options="study_type" :value="scope.row.studyType" /></el-tag>
            </template>
      </el-table-column>
      <el-table-column label="学习时间" align="center" prop="trainTime" />

      <el-table-column :label="type==2?'学习资料':'学习方案'" align="center" prop="trainPlan">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.trainPlan)" v-if="scope.row.trainPlan">查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="签到表" align="center" prop="signList">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.signList)" v-if="scope.row.signList">查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="学习记录表" align="center" prop="record">
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.record)" v-if="scope.row.record">查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
   
 
      <el-table-column label="成绩表" align="center" prop="scores" v-if='queryParams.studyType==2'>
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.scores)" v-if="scope.row.scores">查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="综合评估报告" align="center" prop="assess"  v-if='queryParams.studyType==2'>
        <template #default="scope">
          <el-button @click.stop="previewFun(scope.row.assess)" v-if="scope.row.assess">查看</el-button>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="学习照片" align="center" prop="trainImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.trainImg" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="reportTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reportTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="reporterName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :width="160">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coordination:coo_train:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coordination:coo_train:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改综合学习管理对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="coo_trainRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="收费站" prop="deptId">
              <el-tree-select style="width: 100%;" v-model="form.deptId" :data="deptOptions" :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id" placeholder="请选择" check-strictly />
            </el-form-item>
          </el-col> <el-col :span="12" v-if="type==2">
            <el-form-item label="学习类型" prop="studyType">
              <el-select style="width:100%" v-model="form.studyType" placeholder="请选择学习类型">
                <el-option v-for="dict in study_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> <el-col :span="12">
            <el-form-item label="学习时间" prop="trainTime">
              <el-date-picker style="width: 100%;" clearable v-model="form.trainTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择学习时间">
              </el-date-picker>
            </el-form-item>
          </el-col> <el-col :span="12" v-if="type==2">
          </el-col> <el-col :span="12">
            <el-form-item label="学习资料" prop="trainPlan">
              <file-upload v-model="form.trainPlan" />
            </el-form-item>
        
          </el-col> <el-col :span="12">

            <el-form-item label="签到表" prop="signList">
              <file-upload v-model="form.signList" />
            </el-form-item>
          </el-col> <el-col :span="12">

            <el-form-item label="学习记录表" prop="record">
              <file-upload v-model="form.record" />
            </el-form-item>
          </el-col>
           <el-col :span="12">
<el-form-item label="员工学习名单" prop="nameList">
  <file-upload v-model="form.nameList" />
</el-form-item>
          </el-col> 
          <template v-if="form.studyType==2||type==1">  

    
           <el-col :span="12">
            <el-form-item label="成绩表" prop="scores">
              <file-upload v-model="form.scores" />
            </el-form-item>
          </el-col> <el-col :span="12">
            <el-form-item label="综合评估报告" prop="assess">
              <file-upload v-model="form.assess" />
            </el-form-item>
          </el-col> 
        </template>
          <el-col :span="12">
            <el-form-item label="学习照片" prop="trainImg">
              <image-upload v-model="form.trainImg" />
            </el-form-item>

          </el-col> <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" rows="6" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <Viewer ref="fileViewerRef" :dialog-doc="dialogDoc" />
    <Statistics :echartsData="statisticsData" ref="statisticsRef" @changeType="handleStatistics" />
  </div>
</template>

<script setup name="Coo_train">
import moment from "moment";
import { listCoo_train, getCoo_train, delCoo_train, addCoo_train, updateCoo_train,postTrainCount } from "@/api/coordination/coo_train";
import Viewer from "@/components/Custom/viewer.vue";
import Statistics from "./components/Statistics.vue";
import { getCKInfo } from '@/utils/auth'
import { deptTreeSelect } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { study_type } = proxy.useDict('study_type');

const route = useRoute();
const coo_trainList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptOptions = ref([])
const deptId = ref(Number(getCKInfo('deptId')))
const fileViewerRef = ref()
const dialogDoc = ref(false)
const statisticsData = ref({ series: [{ data: [] }, { data: [] }], xaxis: [] })
const statisticsRef = ref()
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const type=ref()
if (route.query) {
  type.value=route.query.type;
}

// const bindChangeStudyType=(val)=>{
//   if(val==1){
//     // 阅读
//   }
// }
const data = reactive({
  form: {type:type.value},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: deptId.value,
    type:type.value,
    studyType:''
  },
  rules: {
    deptId: [
      { required: true, message: "收费站不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询综合学习管理列表 */
function getList() {
  loading.value = true;
  listCoo_train(queryParams.value).then(response => {
    coo_trainList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: deptId.value,
    type:type.value
  };
  proxy.resetForm("coo_trainRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function handleStatistics(date) {
  // 本年  本季度  本月
  if (!date || !date.startDate) {
    date.startDate = moment().format('YYYY-MM') + '-01'
    date.endDate = moment().endOf('month').format('YYYY-MM-DD')
  }
  statisticsData.value.xaxis = []
  statisticsData.value.series[0].data = []
  postTrainCount({
    "startTime": date.startDate,
    "endTime": date.endDate,
    "type": 1,
  }).then(res => {
    if (res.code == 200 && res.data) {
      res.data.forEach(item => {
        statisticsData.value.xaxis.push(item.deptName)
        statisticsData.value.series[0].data.push(item.openCount)
      })
      statisticsRef.value.open();
    }
  })
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const getTagStyle = (status) => {
  const statusMap = {
    '4': 'danger',
    '3': 'warning',
    '2': 'info',
    '1': 'success',
    '0': 'primary'
  }
  return statusMap[status]
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加综合学习管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCoo_train(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改综合学习管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["coo_trainRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCoo_train(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCoo_train(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除综合学习管理编号为"' + _ids + '"的数据项？').then(function () {
    return delCoo_train(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('coordination/coo_train/export', {
    ...queryParams.value
  }, `学习管理_${new Date().getTime()}.xlsx`)
}
// 预览
const previewFun = (file) => {
  dialogDoc.value = true;
  let data = {};
  // 上传过的文件组成完成的网络路径
  if (file&&file.indexOf(',')==-1) {
    data.src = `${baseUrl}${file}`;
  }else if(file&&file.indexOf(',')!=-1){
    let src=file.split(',');
    let srcArr=[]
    src.forEach(item=>{srcArr.push(`${baseUrl}${item}`)})
    data.src = srcArr.join(',');
    file=srcArr[0]
  }

  const arr = file.split(".");
  const suffix = arr[arr.length - 1];
  if (suffix == "docx" || suffix == "doc") {
    fileViewerRef.value?.viewDocx(data, '班组建设');
  } else if (suffix == "xlsx" || suffix == "xls") {
    fileViewerRef.value?.viewXlsx(data);
  } else if (suffix == "jpg" || suffix == "jpeg" || suffix == "png") {
    fileViewerRef.value?.viewImg(data);
  } else if (suffix == "pdf") {
    fileViewerRef.value?.viewPdf(data);
  }
};
getList();
getDeptTree()
</script>
